package com.xyh.builder;



import com.xyh.bean.Constants;
import com.xyh.utils.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Date;

public class BuildRunApplication {
    private static final Logger logger = LoggerFactory.getLogger(BuildRunApplication.class);

    public static void execute() {
        // 根据包路径生成目标文件路径
        String packagePath = Constants.PACKAGE_BASE.replace(".", "/");
        File runAppDir = new File(Constants.PATH_JAVA + "/" + packagePath);
        File runAppFile = new File(runAppDir, "RunApplication.java");
        try (BufferedWriter bw = new BufferedWriter(
                new OutputStreamWriter(new FileOutputStream(runAppFile), StandardCharsets.UTF_8))) {

            // 包声明和导入
            bw.write("package " + Constants.PACKAGE_BASE + ";\n\n");
            bw.write("import org.mybatis.spring.annotation.MapperScan;\n");
            bw.write("import org.springframework.boot.SpringApplication;\n");
            bw.write("import org.springframework.boot.autoconfigure.SpringBootApplication;\n\n");

            // 类注释
            bw.write("/**\n");
            bw.write(" * @Author: " + Constants.AUTHOR + "\n");
            bw.write(" * @CreateTime: "+ DateUtils.format(new Date(), DateUtils.YYYY_MM_DD_HH_MM_SS)+"\n");
            bw.write(" * @Description: Spring Boot启动类\n");
            bw.write(" * @Version: " + Constants.PROJECT_VERSION + "\n");
            bw.write(" */\n");

            // 类定义
            bw.write("@SpringBootApplication\n");
            bw.write("@MapperScan(basePackages = {\"" + Constants.PACKAGE_MAPPER + "\"})\n");
            bw.write("public class RunApplication {\n");
            // main方法
            bw.write("\tpublic static void main(String[] args) {\n");
            bw.write("\t\tSpringApplication.run(RunApplication.class, args);\n");
            bw.write("\t}\n");
            bw.write("}\n");
            bw.flush();
            logger.info("生成Spring Boot启动类成功: {}", runAppFile.getAbsolutePath());
        } catch (Exception e) {
            logger.error("生成RunApplication失败", e);
        }
    }
}